local function get_from_cache(key)
   local cache_ngx = ngx.shared.cache_upstream
   local value = cache_ngx:get(key)
   return value
end

local function set_to_cache(key, value, exptime)
   if not exptime then
       exptime = 0
   end
   local cache_ngx = ngx.shared.cache_upstream
   local succ, err, forcible = cache_ngx:set(key, value, exptime)
   return succ
end

local hostkey = ngx.var.host_key
local hosts = get_from_cache(hostkey)

if not hosts then
   local redis = require "resty.redis"
  local red = redis:new()

  red:set_timeout(3000) -- 3 sec

  local ok, err = red:connect("127.0.0.1", 6379)
  if not ok then
     ngx.say("failed to connect: ", err)
     return ngx.exit(500)
  end             

  local res, err = red:auth("password")
  if not res then
      ngx.say("failed to authenticate: ", err)
      return ngx.exit(500)
  end

  red:select(15)

  hosts, err = red:hkeys(hostkey)
  if not hosts then
      ngx.say("fail: ", err)
      return ngx.exit(500)
  end

  set_to_cache(hostkey, hosts, 60)
end

local backend = ""  
local port = ngx.var.server_port  
local remote_ip = ngx.var.remote_addr  
local key = remote_ip..port  
local hash = ngx.crc32_long(key)
hash = (hash % #hosts) + 1  

ngx.var.backend = hosts[hash]